package MobileMWClient;

import java.io.*;
import java.net.*;
import java.util.HashMap;
import java.util.Map;

import org.json.simple.JSONValue;

/**
 * <pre>
 * @Package : MWClient
 * @File    : ClientManager.java
 * <pre>
 *
 * @Author  : 차재우
 * @Date    : 2013. 7. 22.
 * @Version :
 */
public class ClientManager {
	private String ip = null;
	private int port = 0;

	private Socket socket = null;
	
	// 시리얼 통신 객체
	private SerialComm serialComm = null;
	
	// 시리얼 송신 대기 큐
	public SerialQueue sendQueue = new SerialQueue();
	
	// 시리얼 수신 대기 큐
	public SerialQueue recvQueue = new SerialQueue();
	
	/**
	 * <pre>
	 * @Comment : 생성자
	 * <pre>
	 *
	 * @param ip
	 * @param port
	 */
	public ClientManager(String ip, int port, String serialPort) {
		this.ip = ip;
		this.port = port;
		
		//InsertTestData();
		
		this.serialComm = new SerialComm(serialPort, recvQueue, sendQueue);
		serialComm.PortOpen();
	}
	
	/**
	 * <pre>
	 * @Comment : 서버 접속 실패시 재접속
	 * <pre>
	 *
	 * @Method  : ReConnect
	 * @return 접속 성공 여부
	 * @throws IOException
	 */
	private boolean ReConnect() throws IOException {
		if(this.socket == null)
		{
			try {
				this.socket = new Socket(ip, port);
			} catch (IOException e) {
				return false;
			}
		}
		return true;
	}

	/**
	 * <pre>
	 * @Comment : 클라이언튼 시작 루틴
	 * <pre>
	 *
	 * @Method  : StartClient
	 * @throws IOException
	 */
	public void StartClient() throws IOException {
		// 최초 접속
		try {
			if(this.socket == null)
				this.socket = new Socket(ip, port);
		} catch (IOException e) {
			this.socket = null;
		}
		
		// 처음 접속 실패시....재접속 시도
		while(this.socket == null) {
			ReConnect();
			
			try {
				Thread.sleep(5 * 1000);
				System.out.println("Try to reconnect.");
			} catch (InterruptedException e) {
				e.printStackTrace();
				
			}
		}

		// 클라이언트 연결 완료 상태
		try {
			if(this.socket.isConnected()) {
				System.out.println("Connected to the server...ok!");

				Thread sender = new Thread(new ClientSender(socket, recvQueue, sendQueue));
				//Thread sender = new Thread(new ClientSender(socket, recvQueue));
				//Thread receiver = new Thread(new ClientReceiver(socket, sendQueue));

				sender.start();
				//receiver.start();
			}
		} catch (Exception e) {
			System.out.println("Socket failed.");
		}
	}
	
	/**
	 * <pre>
	 * @Comment : 테스트 함수 (큐에 임시 데이터 생성)
	 * <pre>
	 *
	 * @Method  : InsertTestData
	 */
	public void InsertTestData() {
		Map<String, String> obj = new HashMap<String, String>();

		obj.put("TRNO", "RM01");
		obj.put("ITYPE", "O");
		obj.put("CSERNO", "S12345");
		obj.put("BTHYMD", "19811220");
		obj.put("SEXCD", "M");
		obj.put("DEPTCD", "01");
		obj.put("ISUNO", "1234");
		obj.put("ISUDT", "20130701");
		obj.put("IOTYPE", "I");

		String jsonStr = JSONValue.toJSONString(obj);
		
		byte[] data = SerialPacket.MakeSerialPacket(jsonStr.getBytes(), 92733210);

		recvQueue.Push(data);
		//recvQueue.Push(data);

		System.out.println("RecvQueue size : " + recvQueue.GetQueueSize());
	}
}
